#include "scene.h"
#include <QPainter>
#include <QGraphicsSimpleTextItem>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
Scene::Scene(qint32 width, qint32 height) : cursor_pos_txt(nullptr)
{
    init();
    // 初始化场景大小
    this->setSceneRect(-(width/2), -(height/2), width, height);
}

void Scene::init()
{
    initBase();
    initPens();

}

void Scene::initPens()
{
    bg_lite_width = 2;
    bg_bold_width = 2;
    bg_pen = QPen(QColor(79, 83, 85));
    bg_pen.setStyle(Qt::PenStyle::SolidLine);
}

void Scene::initBase()
{
    bg_color = QColor("111");
    grid_width = 15;
    big_grid_columns = 5;
}

// 初始化布局
void Scene::initLayout()
{
    QFont font("monospace", 20);
    cursor_pos_txt =new QGraphicsSimpleTextItem();
    cursor_pos_txt->setFont(font);
    cursor_pos_txt->setBrush(QBrush(QColor("white")));
    cursor_pos_txt->setText("0, 0");
    cursor_pos_txt->setPos(0, 0);
    this->addItem(cursor_pos_txt);
}

void Scene::drawBackground(QPainter *painter, const QRectF &rect)
{
    // 绘制背景色
    painter->setBrush(QBrush(bg_color));
    painter->drawRect(rect);

    // 绘制线段
    painter->setPen(bg_pen);
    QVector<QLineF> lite_lines, bold_lines;
    auto left_bound = (qint32)floor(rect.x());
    auto top_bound = (qint32)floor(rect.y());
    auto right_bound = rect.x() + rect.width();
    auto bottom_bound = rect.y() + rect.height();
    auto first_left_x = left_bound - (left_bound % grid_width);
    auto first_top_y = top_bound - (top_bound % grid_width);

    // 上 -> 下 线段
    for(auto i = first_left_x; i < right_bound; i += grid_width) {
        auto line = QLineF(i, top_bound, i, bottom_bound);
        if(i % (big_grid_columns * grid_width) == 0)
            bold_lines.append(line);
        else
            lite_lines.append(line);
    }

    // 左 -> 右 线段
    for(auto i = first_top_y; i < bottom_bound; i += grid_width) {
        auto line = QLineF(left_bound, i,right_bound, i);
        if(i % (big_grid_columns * grid_width) == 0)
            bold_lines.append(line);
        else
            lite_lines.append(line);
    }

    // 绘制
    bg_pen.setWidth(bg_lite_width);
    bg_pen.setColor(QColor(59, 63, 65));
    painter->setPen(bg_pen);
    for(auto& line : lite_lines) painter->drawLine(line);

    bg_pen.setWidth(bg_bold_width);
    bg_pen.setColor(QColor(79, 83, 85));
    painter->setPen(bg_pen);
    for(auto& line : bold_lines) painter->drawLine(line);
}

void Scene::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
    qDebug("scne is ok");
    auto pos = event->scenePos();

    auto show_text = QString("%1, %2").arg(pos.x()).arg(pos.y());
    qDebug() << show_text;
    if(cursor_pos_txt != nullptr)
        cursor_pos_txt->setText(show_text);
    QGraphicsScene::mouseMoveEvent(event);
}
